import { QuestionCircleOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
import {
  Card,
  Radio,
  Switch,
  Tooltip,
  Select,
  Input,
  InputNumber,
  Cascader,
  App,
  Button,
  Collapse,
} from 'antd';
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useLocation } from 'react-router-dom';

import orchestrationService from '@/api/services/orchestrationService';
import { ConfigurationsInfo } from '@/common/types/app/app';
import { CustomFormLabel } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import TipDesc from '@/components/tipDesc/tipDesc';
import useModal from '@/hooks/use-modal/useModal';
import { useMetahumanStore } from '@/store/metahumanStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { StorageEnum } from '@/types/enum';
import { getItem } from '@/utils/storage';

import '../index.css';

import DialogModelSelect from './DialogModelSelect';
import VirtualAvatarConfig from './VirtualAvatarConfig';

const HotQuestionModal = React.lazy(() => import('./HotQuestionModal'));
const InputGuideModal = React.lazy(() => import('./InputGuideModal'));
const RoleTemplateModal = React.lazy(() => import('./RoleTemplateModal'));

// 导入HotQuestion类型
interface HotQuestion {
  id: string;
  content: string;
  answer?: string;
}

// 导入InputGuide类型
interface InputGuide {
  id: string;
  content: string;
}

const DialogSettings: React.FC<{ isPreview?: boolean }> = ({ isPreview = false }) => {
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';

  const [hotQuestionModalVisible, setHotQuestionModalVisible] = useState(false);
  const [inputGuideModalVisible, setInputGuideModalVisible] = useState(false);
  const [roleTemplateModalVisible, setRoleTemplateModalVisible] = useState(false);
  const [verifyBalanceAvailable, setVerifyBalanceAvailable] = useState(true);
  const [textAreaKey, setTextAreaKey] = useState(0);

  const modal = useModal('model');
  const { message } = App.useApp();

  const {
    hotQuestions,
    setHotQuestions,
    inputGuides,
    setInputGuides,
    configurations,
    updateConfiguration,
    appDetail,
    setAppDetail,
    appName,
    appDescription,
    appLogo,
  } = useOrchestrationStore();

  const {
    virtualAvatarEnabled,
    virtualAvatarName,
    virtualAvatarVoice,
    permissionConfig,
    setVirtualAvatarEnabled,
    setVirtualAvatarName,
    setVirtualAvatarVoice,
    setVirtualAvatarId,
    setVirtualSpeakerId,
  } = useMetahumanStore();

  const isMetahumanPermission = useMemo(
    () => permissionConfig?.metahumanPermission,
    [permissionConfig],
  );
  const contentRef = useRef<HTMLDivElement>(null);
  const cardRef = useRef<HTMLDivElement>(null);

  const baseInfoList = ['app_logo', 'scene_image', 'app_name', 'app_description'];
  const orderList = [
    'role_setup',
    'task',
    'opening_remarks',
    'answer_tone',
    'answer_strictness',
    'deep_think',
    'voice_enabled',
    'internet_search',
    'guess_you_want2ask',
    'hot_issues',
    'input_guide',
    'quote_enable',
    'enable_function_calling',
    'enable_nl2sql',
    'enable_application_recommend',
  ];

  const hideList = ['disable_dataset', 'enable_nl2sql_dataset'];

  // 处理虚拟形象设置变化
  const handleVirtualAvatarChange = async (
    avatarName: string,
    voiceType: string,
    avatarId: string,
    speakerId: string,
  ) => {
    try {
      setVirtualAvatarName(avatarName);
      setVirtualAvatarVoice(voiceType);
      setVirtualAvatarId(avatarId);
      setVirtualSpeakerId(speakerId);
      console.log('虚拟形象设置已更新:', { avatarName, voiceType });
    } catch (error) {
      console.error('保存虚拟形象设置失败:', error);
    }
  };

  // 处理角色模板选择
  const handleRoleTemplateSelect = (
    template: {
      key: string;
      label: string;
      roleDescription: string;
      taskDescription: string;
    },
    action: 'replace' | 'append' = 'replace',
  ) => {
    const currentRoleValue =
      (configurations.find((config) => config.name === 'role_setup')?.default_value as string) ||
      '';
    const currentTaskValue =
      (configurations.find((config) => config.name === 'task')?.default_value as string) || '';

    if (action === 'replace') {
      // 替换现有内容
      updateConfiguration('role_setup', template.roleDescription);
      updateConfiguration('task', template.taskDescription);
    } else {
      // 在现有内容后插入
      const newRoleValue = currentRoleValue
        ? `${currentRoleValue}\n\n${template.roleDescription}`
        : template.roleDescription;
      const newTaskValue = currentTaskValue
        ? `${currentTaskValue}\n\n${template.taskDescription}`
        : template.taskDescription;

      updateConfiguration('role_setup', newRoleValue);
      updateConfiguration('task', newTaskValue);
    }

    setTextAreaKey((prev) => prev + 1);

    setTimeout(() => {
      const roleTextArea = document.querySelector(
        'textarea[placeholder*="角色"]',
      ) as HTMLTextAreaElement;
      const taskTextArea = document.querySelector(
        'textarea[placeholder*="任务"]',
      ) as HTMLTextAreaElement;

      if (roleTextArea) {
        roleTextArea.style.height = 'auto';
        roleTextArea.style.height = `${roleTextArea.scrollHeight}px`;
      }
      if (taskTextArea) {
        taskTextArea.style.height = 'auto';
        taskTextArea.style.height = `${taskTextArea.scrollHeight}px`;
      }
    }, 100);

    message.success(`已${action === 'replace' ? '替换' : '插入'}${template.label}模板`);
  };

  // 获取热门问题
  const fetchHotQuestions = async () => {
    if (!appId) return;
    try {
      const res = await orchestrationService.getAppHotIssue(appId);
      if (res.hot_issues) {
        // 转换HotIssue到HotQuestion
        const questions = res.hot_issues.map((issue, index) => ({
          id: String(index + 1),
          content: issue.content,
          answer: issue.answer,
        }));
        setHotQuestions(questions);
      }
    } catch (error) {
      message.error('获取热门问题失败');
    }
  };

  // 更新热门问题
  const updateHotQuestions = async (questions: HotQuestion[]) => {
    if (!appId) {
      message.error('应用ID不存在');
      return;
    }
    try {
      await orchestrationService.updateAppHotIssue(appId, {
        hot_issues: questions.map((q) => ({
          content: q.content,
          answer: q.answer || '', // 使用问题中的answer字段
        })),
      });
      setHotQuestions(questions);
      message.success('热门问题更新成功');
    } catch (error) {
      message.error('热门问题更新失败');
    }
  };

  // 修改保存热门问题的方法
  const saveHotQuestions = async (questions: HotQuestion[]) => {
    setHotQuestions(questions);
    await updateHotQuestions(questions);
  };

  // 获取输入引导
  const fetchInputGuides = async () => {
    if (!appId) return;
    try {
      const res = await orchestrationService.getAppInputGuide(appId);
      if (res.input_guide) {
        const guides = res.input_guide.map((guide: string, index: number) => ({
          id: String(index + 1),
          content: guide,
        }));
        setInputGuides(guides);
      }
    } catch (error) {
      message.error('获取输入引导失败');
    }
  };

  // 更新输入引导
  const updateInputGuides = async (guides: InputGuide[]) => {
    if (!appId) {
      message.error('应用ID不存在');
      return;
    }
    try {
      await orchestrationService.updateAppInputGuide(appId, {
        input_guide: guides.map((g) => g.content),
      });
      message.success('输入引导更新成功');
    } catch (error) {
      message.error('输入引导更新失败');
    }
  };

  // 验证余额
  const verifyBalance = async () => {
    const res = await orchestrationService.verifyBalance(appId);
    setVerifyBalanceAvailable(res);
  };

  // 组件加载时获取输入引导
  useEffect(() => {
    fetchInputGuides();
    fetchHotQuestions();
    verifyBalance();
  }, [appId]);

  // 修改保存输入引导的方法
  const saveInputGuides = async (guides: InputGuide[]) => {
    setInputGuides(guides);
    await updateInputGuides(guides);
  };

  // 热门问题相关方法
  const openHotQuestionModal = () => {
    setHotQuestionModalVisible(true);
  };

  const closeHotQuestionModal = () => {
    setHotQuestionModalVisible(false);
  };

  // 输入引导相关方法
  const openInputGuideModal = () => {
    setInputGuideModalVisible(true);
  };

  const closeInputGuideModal = () => {
    setInputGuideModalVisible(false);
  };

  // 角色模板相关方法
  const openRoleTemplateModal = () => {
    setRoleTemplateModalVisible(true);
  };

  const closeRoleTemplateModal = () => {
    setRoleTemplateModalVisible(false);
    // 确保模态框关闭后父组件能正确渲染
    setTextAreaKey((prev) => prev + 1);
  };

  // 渲染动态配置项
  const renderConfigItem = (config: ConfigurationsInfo) => {
    const {
      name,
      type,
      description,
      default_value,
      max_length,
      max_value,
      min_value,
      list_value = [],
    } = config;
    const label = description || name;

    // 定义配置项对应的 Tooltip 内容
    const tooltipMap: Record<string, string> = {
      role_setup: '应该扮演一个什么样的角色，角色背景是什么？',
      task: '此应用有什么任务需要执行',
      opening_remarks: '开场欢迎语',
      internet_search: '允许AI在回答问题时进行联网搜索',
      deep_think: '允许对话使用深度思考，大模型会进行深度思考后回复答案',
      guess_you_want2ask: '对话结束后，会为生成3个引导性问题',
      input_guide:
        '可以配置一些预设的问题。在用户输入问题时，会从这些预设问题中获取相关问题进行提示',
      hot_issues: '每次对话展示预设问题，最多5个固定的问题，指引用户使用',
      quote_enable: '在回答中显示引用的知识库内容',
      enable_nl2sql: '开启后用户可以通过自然对话的方式获取到数据库里面的信息，实现交互式问数。',
      enable_function_calling:
        '开启后用户能通过自然对话的方式获取到"数据管理"接口背后的信息，实现交互式问数',
      enable_application_recommend:
        '开启后系统能在问答的同时，给用户推荐最相关的应用入口，方便用户快速完成业务办理',
    };

    const maxToken: Record<string, number> = {
      role_setup: 200,
      task: 1000,
      opening_remarks: 50,
    };

    // 定义选项配置
    const optionConfig: Record<string, Record<string, { label: string; description: string }>> = {
      answer_tone: {
        official: { label: '官方', description: '语气正式、直白' },
        neutral: { label: '中性', description: '语气平和、客观' },
        moderate: { label: '中性', description: '语气平和、客观' },
        lively: { label: '活泼', description: '语气热情、轻松' },
      },
      answer_strictness: {
        strict: { label: '严谨', description: '仅回答知识库内容' },
        moderate: { label: '中性', description: '适度扩展知识库内容' },
        neutral: { label: '中性', description: '适度扩展知识库内容' },
        random: { label: '发散', description: '自由延展话题' },
      },
    };

    // 根据类型渲染不同的控件
    switch (type) {
      case 'numberInput':
        return (
          <div key={name} className="flex items-center justify-between">
            <div className="flex items-center">
              <div className="font text-text-4">
                {label}
                <span className="ml-1 text-xs text-error">*</span>
              </div>
              {tooltipMap[name] && (
                <Tooltip title={tooltipMap[name]}>
                  <QuestionCircleOutlined className="ml-1 text-xs text-[#86909C]" />
                </Tooltip>
              )}
            </div>
            {min_value === 0 && max_value === 0 ? (
              <InputNumber
                value={typeof default_value === 'number' ? default_value : Number(default_value)}
                onChange={(value) => updateConfiguration(name, value ?? 0)}
                disabled={isPreview}
              />
            ) : (
              <InputNumber
                min={min_value}
                max={max_value}
                value={typeof default_value === 'number' ? default_value : Number(default_value)}
                onChange={(value) => updateConfiguration(name, value ?? 0)}
                disabled={isPreview}
              />
            )}
          </div>
        );

      case 'input':
        return (
          <div key={name}>
            <div className="my-2 flex items-center justify-between">
              <CustomFormLabel
                description={
                  name === 'role_setup'
                    ? '在此定义智能体的核心身份定位、人格特点和互动风格'
                    : name === 'task'
                    ? '在此定义智能体的核心职责或主要目标'
                    : name === 'opening_remarks'
                    ? '设置用户首次与智能体对话时，智能体主动发送的第一条消息内容'
                    : ''
                }
                required
                prefix
              >
                {label}
              </CustomFormLabel>
              {/* {!getItem(StorageEnum.TiangongManagerRoles) && name === 'role_setup' && !isPreview && ( */}
              {!(
                (getItem(StorageEnum.User) as any)?.is_TianGong === 'true' ||
                (getItem(StorageEnum.User) as any)?.is_TianGong === true
              ) &&
                name === 'role_setup' &&
                !isPreview && (
                  <Button color="default" variant="outlined" onClick={openRoleTemplateModal}>
                    <SvgIcon icon="icon_roleTemplate" size={16} />
                    从模板选择
                  </Button>
                )}
            </div>
            <div className="relative text-[14px] text-[#424242]">
              <Input.TextArea
                key={name === 'role_setup' || name === 'task' ? `${name}-${textAreaKey}` : name}
                className="w-full resize-none rounded-md border p-2 [-ms-overflow-style:none] [scrollbar-width:none] focus:border-[#D9D9D9] focus:outline-none"
                maxLength={max_length || maxToken?.[name] || 100}
                value={default_value as string}
                onChange={(e) => updateConfiguration(name, e.target.value)}
                placeholder={tooltipMap?.[name] || ''}
                style={{ borderColor: '#D9D9D9', paddingBottom: '24px' }}
                autoSize={{ minRows: 3, maxRows: 6 }}
                disabled={isPreview}
              />
              {/* {(max_length !== undefined && max_length > 0) ||
                (maxToken?.[name] > 0 && (
                  <div className="absolute bottom-2 right-2 text-[14px] text-[#A5A9BB]">
                    {(default_value as string)?.length || 0} / {max_length || maxToken?.[name]}
                  </div>
                ))} */}
              <div className="absolute bottom-2 right-2 text-[14px] text-[#A5A9BB]">
                {(default_value as string)?.length || 0} / {max_length || maxToken?.[name] || 100}
              </div>
            </div>
          </div>
        );

      case 'select':
        if (list_value.length <= 6) {
          return (
            <div key={name} className="py-2">
              <div className="mb-4 flex items-center">
                {/* <div className="font-normal text-text-4">
                  {label}
                  <span className="ml-1 text-xs text-error">*</span>
                </div> */}
                <CustomFormLabel prefix required>
                  {label}
                </CustomFormLabel>
                {tooltipMap[name] && (
                  <Tooltip title={tooltipMap[name]}>
                    <QuestionCircleOutlined className="ml-1 text-xs text-[#86909C]" />
                  </Tooltip>
                )}
              </div>
              <Radio.Group
                value={default_value}
                onChange={(e) => updateConfiguration(name, e.target.value)}
                className="w-full"
                disabled={isPreview}
              >
                <div className="grid grid-cols-3 gap-4">
                  {list_value.map((option) => (
                    <div
                      key={option}
                      className={`custom-radio cursor-pointer rounded-md border p-2 text-[14px] ${
                        default_value === option
                          ? 'border-[#1B6DFA] bg-[#F0F7FF] font-semibold text-@brand-color'
                          : 'border-[#E5E6EB] font-normal text-text-4'
                      } ${isPreview ? 'cursor-default' : ''}`}
                    >
                      <Radio value={option} className="w-full">
                        {['answer_tone', 'answer_strictness'].includes(name) &&
                        optionConfig?.[name]?.[option] ? (
                          <div className="flex flex-col">
                            <div
                              className={`flex items-center justify-center text-[14px]
                                ${default_value === option ? 'text-@brand-color' : 'text-text-4'}
                              `}
                            >
                              {optionConfig[name][option].label}
                            </div>
                            {/* <div className="flex items-center justify-center text-[10px] text-[#BFBFBF]">
                              {optionConfig[name][option].description}
                            </div> */}
                          </div>
                        ) : (
                          <div
                            className={`text-[14px] 
                          ${default_value === option ? 'text-@brand-color' : 'text-text-4'}
                          `}
                          >
                            {option}
                          </div>
                        )}
                      </Radio>
                    </div>
                  ))}
                </div>
              </Radio.Group>
            </div>
          );
        }
        return (
          <div key={name} className="flex items-center justify-between py-2">
            <div className="flex items-center">
              <div className="font-normal text-text-4">
                {label}
                <span className="ml-1 text-xs text-error">*</span>
              </div>
              {tooltipMap[name] && (
                <Tooltip title={tooltipMap[name]}>
                  <QuestionCircleOutlined className="ml-1 text-xs text-[#86909C]" />
                </Tooltip>
              )}
            </div>
            <Select
              style={{ width: 200 }}
              value={default_value as string}
              onChange={(value) => updateConfiguration(name, value)}
              options={list_value.map((option) => ({ label: option, value: option }))}
              disabled={isPreview}
            />
          </div>
        );

      case 'boolean':
        // 定义每个配置项的 TipDesc 文案
        const getTipDescTitle = (configName: string) => {
          const tipDescMap: Record<string, string> = {
            voice_enabled: '开启后，用户可以通过语音方式愉入问题或指令',
            deep_think: '此功能使智能体在响应前进行更深入的分析和思考',
            guess_you_want2ask: '对话结束后，智能体会主动猜测用户可能想问的问题并展示给用户选择',
            internet_search:
              '开启后，当智能体自身知识库无法满足用户问题需求时，它可以自动连接到互联网搜索最新信息来补充或验证答案',
            quote_enable:
              '智能体在回答问题时，如果答案来源于其关联的知识库文档，会在回复中明确标注引用的来源文档信息',
            enable_nl2sql:
              '开启后用户可以通过自然对话的方式获取到数据库里面的信息，实现交互式问数。',
            hot_issues: '配置一组最常被用户问到的问题列表，每次对话展示预设问题',
            input_guide: '配置在用户输入框中显示的引导问题',
            enable_function_calling:
              '开启后用户能通过自然对话的方式获取到"数据管理"接口背后的信息，实现交互式问数',
            enable_application_recommend:
              '智能推荐相关应用入口，在问答过程中为用户提供便捷的业务办理通道',
          };
          return tipDescMap[configName] || '';
        };

        return (
          <div
            key={name}
            style={{
              display: hideList.includes(name) ? 'none' : undefined,
            }}
            className="my-2 flex items-center justify-between rounded-md bg-[#F8F9FA] px-3 py-2"
          >
            <div className="flex flex-col">
              <div className="flex items-center">
                {/* 根据配置项名称显示对应的图标 */}
                <div className="mr-2 flex h-5 w-5 items-center justify-center">
                  {name === 'voice_enabled' && (
                    <SvgIcon icon="chat-setting-microphone" size={20} color="var(--brand-color)" />
                  )}
                  {name === 'deep_think' && (
                    <SvgIcon icon="chat-setting-deepThink" size={20} color="var(--brand-color)" />
                  )}
                  {name === 'guess_you_want2ask' && (
                    <SvgIcon
                      icon="chat-setting-guessYouWant"
                      size={20}
                      color="var(--brand-color)"
                    />
                  )}
                  {name === 'internet_search' && (
                    <SvgIcon
                      icon="chat-setting-internetSearch"
                      size={20}
                      color="var(--brand-color)"
                    />
                  )}
                  {name === 'quote_enable' && (
                    <SvgIcon icon="chat-setting-quoteEnable" size={20} color="var(--brand-color)" />
                  )}
                  {name === 'enable_nl2sql' && (
                    <SvgIcon icon="ai-orch-nl2sql" size={20} color="var(--brand-color)" />
                  )}
                  {name === 'hot_issues' && (
                    <SvgIcon icon="chat-setting-hotIssues" size={20} color="var(--brand-color)" />
                  )}
                  {name === 'input_guide' && (
                    <SvgIcon icon="chat-setting-inputGuide" size={20} color="var(--brand-color)" />
                  )}
                  {name === 'enable_function_calling' && (
                    <SvgIcon
                      icon="chat-setting-IntelligentQuestion"
                      size={20}
                      color="var(--brand-color)"
                    />
                  )}
                  {name === 'enable_application_recommend' && (
                    <SvgIcon
                      icon="chat-setting-recommendedApplication"
                      size={20}
                      color="var(--brand-color)"
                    />
                  )}
                </div>
                <div className="font-normal leading-5 text-text-5">
                  {label}
                  {name === 'internet_search' && !verifyBalanceAvailable && (
                    <span className="text-xs text-text-3">（暂不支持使用）</span>
                  )}
                </div>
                {/* {tooltipMap[name] && (
                  <Tooltip title={tooltipMap[name]}>
                    <QuestionCircleOutlined className="ml-1 text-xs text-[#86909C]" />
                  </Tooltip>
                )} */}
              </div>

              {/* 为每个配置项添加 TipDesc 组件 */}
              {getTipDescTitle(name) && (
                <TipDesc title={getTipDescTitle(name)} className="!mt-1 pr-5" />
              )}
            </div>
            <div className="flex items-center gap-2">
              {(name === 'hot_issues' || name === 'input_guide') && (
                <div
                  className={`pr-5 text-[14px]
                     text-text-3
                    ${isPreview ? 'cursor-default' : 'cursor-pointer hover:text-[#1677ff]'}`}
                  onClick={() =>
                    !isPreview &&
                    (name === 'hot_issues' ? openHotQuestionModal() : openInputGuideModal())
                  }
                >
                  已配置{name === 'hot_issues' ? hotQuestions.length : inputGuides.length}个
                  {name === 'hot_issues' ? '问题' : '引导'}&gt;&gt;
                </div>
              )}
              <Switch
                checked={default_value == '1' || default_value == 1 || default_value == true}
                onChange={(checked) => updateConfiguration(name, checked)}
                className="bg-gray-300"
                disabled={isPreview || (name === 'internet_search' && !verifyBalanceAvailable)}
              />
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  const handleSelectSubmit = (value: any) => {
    console.log(value);
    setAppDetail({
      ...appDetail,
      app_name:
        configurations.find((config) => config.name === 'app_name')?.default_value || appName,
      app_description:
        configurations.find((config) => config.name === 'app_description')?.default_value ||
        appDescription ||
        '',
      app_logo:
        configurations.find((config) => config.name === 'app_logo')?.default_value || appLogo,
      configurations,
      model: value,
    });
    modal.model.close();
  };

  return (
    <Card
      className="orch-card-body relative mb-4 h-full overflow-auto [-ms-overflow-style:none] [scrollbar-width:none]"
      ref={cardRef}
    >
      <div ref={contentRef} className="mb-2 mt-2 max-h-[calc(100vh-280px)]">
        <CustomFormLabel
          className="mb-2"
          prefix
          required
          description="用于选择和切换支撑智能体对话能力的底层大型语言模型（LLM）"
        >
          对话模型
        </CustomFormLabel>

        <Cascader
          options={[]}
          onClick={isPreview ? () => {} : modal.model.open}
          open={false}
          style={{ width: '100%' }}
          value={appDetail.model?.model ? appDetail.model.model : ''}
          placeholder="请选择你的模型"
          clearIcon={false}
          disabled={isPreview}
          // value={appDetail.model.name}
        />

        {/* 动态配置项 */}
        {configurations.length > 0 && (
          <div className="mt-1 pb-5 pt-1">
            {/* <div className="space-y-6"> */}
            <div>
              {/* 非布尔类型配置项 */}
              {configurations
                .filter(
                  (config) => !baseInfoList.includes(config.name) && config.type !== 'boolean',
                )
                .sort((a, b) => {
                  const indexA = orderList.indexOf(a.name);
                  const indexB = orderList.indexOf(b.name);
                  if (indexA === -1 && indexB === -1) return 0;
                  if (indexA === -1) return 1;
                  if (indexB === -1) return -1;
                  return indexA - indexB;
                })
                .map(renderConfigItem)}

              {/* 布尔类型配置项分组 */}
              <Collapse
                defaultActiveKey={[]}
                ghost
                expandIconPosition="end"
                expandIcon={({ isActive }) => (isActive ? <UpOutlined /> : <DownOutlined />)}
                style={{ marginTop: '20px' }}
                className="[&_.ant-collapse-content-box]:!p-0 [&_.ant-collapse-content]:!p-0 [&_.ant-collapse-header]:!p-0 [&_.ant-collapse-item]:mb-4"
                items={[
                  {
                    key: '1',
                    label: <CustomFormLabel prefix>对话体验</CustomFormLabel>,
                    children: (
                      <div className="space-y-2">
                        {isMetahumanPermission && (
                          <VirtualAvatarConfig
                            isPreview={isPreview}
                            enabled={virtualAvatarEnabled}
                            onToggle={setVirtualAvatarEnabled}
                            avatarName={virtualAvatarName}
                            voiceType={virtualAvatarVoice}
                            onAvatarChange={handleVirtualAvatarChange}
                          />
                        )}
                        {[
                          /** 语音输入 * */
                          'voice_enabled',
                          /** 深度思考 * */
                          'deep_think',
                          /** 猜你想问 * */
                          'guess_you_want2ask',
                          /** 联网搜索 * */
                          'internet_search',
                          /** 文档引用 * */
                          'quote_enable',
                        ]
                          .map((configName) =>
                            configurations.find(
                              (config) => config.type === 'boolean' && config.name === configName,
                            ),
                          )
                          .filter(Boolean)
                          .map(renderConfigItem)}
                      </div>
                    ),
                    style: {
                      display:
                        configurations.some(
                          (config) =>
                            config.type === 'boolean' &&
                            [
                              /** 语音输入 * */
                              'voice_enabled',
                              /** 深度思考 * */
                              'deep_think',
                              /** 猜你想问 * */
                              'guess_you_want2ask',
                              /** 联网搜索 * */
                              'internet_search',
                              /** 文档引用 * */
                              'quote_enable',
                            ].includes(config.name),
                        ) || isMetahumanPermission
                          ? undefined
                          : 'none',
                    },
                  },
                  {
                    key: '2',
                    label: <CustomFormLabel prefix>智能搜索</CustomFormLabel>,
                    children: (
                      <div className="space-y-2">
                        {configurations
                          .filter(
                            (config) =>
                              config.type === 'boolean' &&
                              [
                                /** 热门问题 * */
                                'hot_issues',
                                /** 输入引导 * */
                                'input_guide',
                              ].includes(config.name),
                          )
                          .map(renderConfigItem)}
                      </div>
                    ),
                    style: {
                      display: configurations.some(
                        (config) =>
                          config.type === 'boolean' &&
                          [
                            /** 热门问题 * */
                            'hot_issues',
                            /** 输入引导 * */
                            'input_guide',
                          ].includes(config.name),
                      )
                        ? undefined
                        : 'none',
                    },
                  },
                  {
                    key: '3',
                    label: <CustomFormLabel prefix>高级设置</CustomFormLabel>,
                    children: (
                      <div className="space-y-2">
                        {configurations
                          .filter(
                            (config) =>
                              config.type === 'boolean' &&
                              [
                                /** 智能问数 * */
                                'enable_function_calling',
                                /** 应用推荐 * */
                                'enable_application_recommend',
                                /** 自然问数 * */
                                'enable_nl2sql',
                              ].includes(config.name),
                          )
                          .sort((a, b) => {
                            const indexA = orderList.indexOf(a.name);
                            const indexB = orderList.indexOf(b.name);
                            if (indexA === -1 && indexB === -1) return 0;
                            if (indexA === -1) return 1;
                            if (indexB === -1) return -1;
                            return indexA - indexB;
                          })
                          .map(renderConfigItem)}
                      </div>
                    ),
                    style: {
                      display: configurations.some(
                        (config) =>
                          config.type === 'boolean' &&
                          [
                            /** 智能问数 * */
                            'enable_function_calling',
                            /** 应用推荐 * */
                            'enable_application_recommend',
                            /** 自然问数 * */
                            'enable_nl2sql',
                          ].includes(config.name),
                      )
                        ? undefined
                        : 'none',
                    },
                  },
                ]}
              />
            </div>
          </div>
        )}
      </div>

      {/* 热门问题配置Modal */}
      <HotQuestionModal
        visible={hotQuestionModalVisible}
        onClose={closeHotQuestionModal}
        initialQuestions={hotQuestions}
        onSave={saveHotQuestions}
      />

      {/* 输入引导配置Modal */}
      <InputGuideModal
        visible={inputGuideModalVisible}
        onClose={closeInputGuideModal}
        initialGuides={inputGuides}
        onSave={saveInputGuides}
      />

      {/* 角色模板选择Modal */}
      <RoleTemplateModal
        visible={roleTemplateModalVisible}
        onClose={closeRoleTemplateModal}
        onSelect={handleRoleTemplateSelect}
        currentRoleValue={
          (configurations.find((config) => config.name === 'role_setup')
            ?.default_value as string) || ''
        }
        currentTaskValue={
          (configurations.find((config) => config.name === 'task')?.default_value as string) || ''
        }
      />

      <DialogModelSelect
        open={modal.model.isOpen}
        defaultValue={appDetail?.model}
        onCancel={modal.model.close}
        onSubmit={handleSelectSubmit}
        isWorkflow={false}
      />
    </Card>
  );
};

export default DialogSettings;
